package cn.sonui.onlinechat.controller;

import cn.sonui.onlinechat.bean.RoomInfo;
import cn.sonui.onlinechat.bean.UserInfo;
import cn.sonui.onlinechat.utils.OnlineChat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

import static cn.sonui.onlinechat.utils.OnlineChat.*;

@Controller
public class Login {
    @RequestMapping("/login")
    public String onLogin(
            @RequestParam(name = "name", required = false) String name,
            @RequestParam(name = "password", required = false) String password,
            HttpServletRequest request,
            HttpServletResponse response,
            ModelMap map
    ) {
        HttpSession session = request.getSession();
        AtomicReference<Boolean> isLogin = new AtomicReference<>((Boolean) session.getAttribute("login"));

        List<Map<String, String>> alertList = new ArrayList<>();

        if (Boolean.TRUE.equals(isLogin.get())) return "redirect:rooms";
        isLogin.set(false);//去掉null
        if (name != null && password != null){//登录

            //判断用户缓存中是否有该用户，存在验证密码，不存在执行注册
            AtomicReference<Boolean> inUserCache = new AtomicReference<>(false);
            userCache.forEach((id, info) -> {
                if (info.getName().equals(name)){
                    isLogin.set(info.getPassword().equals(password));
                    inUserCache.set(true);
                    session.setAttribute("login", isLogin.get());
                    session.setAttribute("uid", info.getId());
                }
            });

            if (!inUserCache.get()){//未注册
                UserInfo user = new UserInfo();
                user.setName(name);
                user.setPassword(password);
                user.setHeader("Lv1");
                user.setRooms(new ArrayList<>(1));
                int uid;
                synchronized(userCache){
                    Integer[] list = userCache.keySet().toArray(new Integer[0]);
                    Arrays.sort(list);
                    uid = list.length == 0 ? 1 : list[list.length - 1] + 1;
                }

                user.setId(uid);
                userCache.put(uid, user);

                RoomInfo t = roomCache.get(1);
                if (t == null) {
                    OnlineChat k = new OnlineChat();
                    k.init();
                }
                t = roomCache.get(1);
                List<Integer> c = t.getMember();
                c.add(uid);
                t.setMember(c);
                roomCache.put(1, t);

                inUserCache.set(true);
                isLogin.set(true);
                session.setAttribute("login", true);
                session.setAttribute("uid", uid);
            }else if(!isLogin.get()){//存在但密码错误
                Map<String, String> alert = new HashMap<>();
                alert.put("content", "密码错误");
                alert.put("class", "alert alert-danger alert-dismissible fade show");
                alert.put("bt", "btn-close");
                alertList.add(alert);
            }

            session.setAttribute("login", isLogin.get());
            if (isLogin.get()){
                response.addCookie(new Cookie("token", session.getId()));
                livingCache.put(session.getId(), (Integer) session.getAttribute("uid"));
            }
            map.put("alert", alertList);
            return isLogin.get() ? "redirect:rooms" : "login";
        }else {
            return "login";
        }

    }
}
